package org.jeecg.modules.my.zhisk.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.my.zhisk.vo.ZhiskTreeModel;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.my.zhisk.entity.ZhiskWenz;
import org.jeecg.modules.my.zhisk.entity.ZhiskLanm;
import org.jeecg.modules.my.zhisk.vo.ZhiskLanmPage;
import org.jeecg.modules.my.zhisk.service.IZhiskLanmService;
import org.jeecg.modules.my.zhisk.service.IZhiskWenzService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 知识库栏目
 * @Author: jeecg-boot
 * @Date: 2021-08-21
 * @Version: V1.0
 */
@Api(tags = "知识库栏目")
@RestController
@RequestMapping("/zhisk/zhiskLanm")
@Slf4j
public class ZhiskLanmController {
    @Autowired
    private IZhiskLanmService zhiskLanmService;
    @Autowired
    private IZhiskWenzService zhiskWenzService;

    // 根节点的parentId为空才行
    @GetMapping(value = "/queryTreeList")
    public Result<List<ZhiskTreeModel>> queryTreeList(String key) {
        String sysOrgCode = "";
        String position = "";

        // 权限判断
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            sysOrgCode = sysUser.getOrgCode();
            position = sysUser.getPost();
        }

        Result<List<ZhiskTreeModel>> result = new Result<>();
        try {
            List<ZhiskTreeModel> list = zhiskLanmService.queryTreeList(key);
            result.setResult(list);
            result.setSuccess(true);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 分页列表查询
     *
     * @param zhiskLanm
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "知识库栏目-分页列表查询")
    @ApiOperation(value = "知识库栏目-分页列表查询", notes = "知识库栏目-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ZhiskLanm zhiskLanm,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ZhiskLanm> queryWrapper = QueryGenerator.initQueryWrapper(zhiskLanm, req.getParameterMap());
        Page<ZhiskLanm> page = new Page<ZhiskLanm>(pageNo, pageSize);
        IPage<ZhiskLanm> pageList = zhiskLanmService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param zhiskLanmPage
     * @return
     */
    @AutoLog(value = "知识库栏目-添加")
    @ApiOperation(value = "知识库栏目-添加", notes = "知识库栏目-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ZhiskLanmPage zhiskLanmPage) {
        ZhiskLanm zhiskLanm = new ZhiskLanm();
        BeanUtils.copyProperties(zhiskLanmPage, zhiskLanm);

        List<ZhiskWenz> zhiskWenzList = new ArrayList<>();
        ZhiskWenz zhiskWenz = new ZhiskWenz();
        zhiskWenz.setWenzbt(zhiskLanm.getLanmmc());
        zhiskWenz.setWenznr("");
        zhiskWenzList.add(zhiskWenz);

        zhiskLanm.setDeleteFlag(0);
        zhiskLanmService.saveMain(zhiskLanm, zhiskWenzList);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param zhiskLanmPage
     * @return
     */
    @AutoLog(value = "知识库栏目-编辑")
    @ApiOperation(value = "知识库栏目-编辑", notes = "知识库栏目-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ZhiskLanmPage zhiskLanmPage) {
        ZhiskLanm zhiskLanm = new ZhiskLanm();
        BeanUtils.copyProperties(zhiskLanmPage, zhiskLanm);
        ZhiskLanm zhiskLanmEntity = zhiskLanmService.getById(zhiskLanm.getId());
        if (zhiskLanmEntity == null) {
            return Result.error("未找到对应数据");
        }
        zhiskLanmService.updateMain(zhiskLanm, zhiskLanmPage.getZhiskWenzList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "知识库栏目-通过id删除")
    @ApiOperation(value = "知识库栏目-通过id删除", notes = "知识库栏目-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        zhiskLanmService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "知识库栏目-批量删除")
    @ApiOperation(value = "知识库栏目-批量删除", notes = "知识库栏目-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.zhiskLanmService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "知识库栏目-通过id查询")
    @ApiOperation(value = "知识库栏目-通过id查询", notes = "知识库栏目-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ZhiskLanm zhiskLanm = zhiskLanmService.getById(id);
        if (zhiskLanm == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(zhiskLanm);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "知识库文章通过主表ID查询")
    @ApiOperation(value = "知识库文章主表ID查询", notes = "知识库文章-通主表ID查询")
    @GetMapping(value = "/queryZhiskWenzByMainId")
    public Result<?> queryZhiskWenzListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ZhiskWenz> zhiskWenzList = zhiskWenzService.list(new LambdaQueryWrapper<ZhiskWenz>().orderByAsc(ZhiskWenz::getSequence).eq(ZhiskWenz::getZhubId, id));
        return Result.OK(zhiskWenzList);
    }

    @GetMapping(value = "/queryZhiskWenzByMainIdWithP")
    public Result<?> queryZhiskWenzByMainIdWithP(@RequestParam(name = "id", required = true) String id) {
        List<ZhiskWenz> zhiskWenzList = zhiskWenzService.list(new LambdaQueryWrapper<ZhiskWenz>().eq(ZhiskWenz::getZhubId, id)); //zhiskWenzService.selectByMainId(id);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser != null) {
            String sysOrgCode = sysUser.getOrgCode();
            String position = sysUser.getPost();
            List<ZhiskWenz> rstList = zhiskWenzList.stream().filter(wz -> {
                        boolean orgFlag = true, positionFlag = true;

                        if (CollectionUtils.isNotEmpty(wz.getOrgOwn())) {
                            orgFlag = wz.getOrgOwn().contains(sysOrgCode);
                        }
                        if (CollectionUtils.isNotEmpty(wz.getPositionOwn())) {
                            positionFlag = wz.getPositionOwn().contains(position);
                        }
                        return orgFlag && positionFlag;
                    }
//                CollectionUtils.exists(wz.getOrgOwn(),org -> StringUtils.equals(sysOrgCode,org.toString()))
//                        && CollectionUtils.exists(wz.getPositionOwn(),p -> StringUtils.equals(position,p.toString()))
            ).collect(Collectors.toList());

            if (CollectionUtils.size(zhiskWenzList) > 0 && CollectionUtils.size(rstList) > 0) {
                return Result.OK(rstList);
            }
            if (CollectionUtils.size(zhiskWenzList) > 0 && CollectionUtils.size(rstList) == 0) {
                return Result.error("没有查看权限");
            }
            if (CollectionUtils.size(zhiskWenzList) == 0) {
                return Result.error("暂无数据");
            }
        }
        if (CollectionUtils.isNotEmpty(zhiskWenzList)) {
            return Result.OK(zhiskWenzList);
        } else {
            return Result.error("暂无数据");
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param zhiskLanm
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZhiskLanm zhiskLanm) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ZhiskLanm> queryWrapper = QueryGenerator.initQueryWrapper(zhiskLanm, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<ZhiskLanm> queryList = zhiskLanmService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<ZhiskLanm> zhiskLanmList = new ArrayList<ZhiskLanm>();
        if (oConvertUtils.isEmpty(selections)) {
            zhiskLanmList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            zhiskLanmList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<ZhiskLanmPage> pageList = new ArrayList<ZhiskLanmPage>();
        for (ZhiskLanm main : zhiskLanmList) {
            ZhiskLanmPage vo = new ZhiskLanmPage();
            BeanUtils.copyProperties(main, vo);
            List<ZhiskWenz> zhiskWenzList = zhiskWenzService.selectByMainId(main.getId());
            vo.setZhiskWenzList(zhiskWenzList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "知识库栏目列表");
        mv.addObject(NormalExcelConstants.CLASS, ZhiskLanmPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("知识库栏目数据", "导出人:" + sysUser.getRealname(), "知识库栏目"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZhiskLanmPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZhiskLanmPage.class, params);
                for (ZhiskLanmPage page : list) {
                    ZhiskLanm po = new ZhiskLanm();
                    BeanUtils.copyProperties(page, po);
                    zhiskLanmService.saveMain(po, page.getZhiskWenzList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
